package com.fire.dao.impl;

import com.fire.dao.IStudentDao;
import com.fire.domain.Student;
import com.fire.util.ExportExcel;
import com.fire.util.POIUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StudentDaoImpl implements IStudentDao {
    private static ArrayList<Student> list = new ArrayList<>();
    static {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("students.txt"));
            String line;

            while ((line = reader.readLine()) != null) {
                String[] studentsplit = line.split(",");
                Student student = new Student(studentsplit[0], studentsplit[1], studentsplit[2],
                        LocalDate.parse(studentsplit[3]), studentsplit[4], Integer.parseInt(studentsplit[5]), Integer.parseInt(studentsplit[6]),
                        studentsplit[7]);
                list.add(student);
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ddd.txt"));
                oos.writeObject(student);
                oos.close();
            }
            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void add(Student student) {
        list.add(student);
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("students.txt", true));
            bufferedWriter.newLine();
            bufferedWriter.write(student.getId() + "," + student.getName() + "," + student.getGender() + "," + student.getBirthday() + "," + student.getPhoneNum() + ","
                    + student.getAge() + "," + student.getGroup() + "," + student.getWeChatNum());
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(String id) throws IOException {
        int index = getIndex(id);
        list.remove(index);
        BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"));
        for (Student student : list) {
            writer.write(student.getId() + "," + student.getName() + "," + student.getGender() + "," + student.getBirthday() + "," + student.getPhoneNum() + ","
                    + student.getAge() + "," + student.getGroup() + "," + student.getWeChatNum());
        }
        writer.close();
    }

    @Override
    public ArrayList<Student> findAll() {
        return list;
    }

    @Override
    public int getIndex(String id) {
        if (list == null || list.size() == 0) {
            return -1;
        }
        for (int i = 0; i < list.size(); i++) {
            Student student = list.get(i);
            if (student.getId().equals(id)) {
                return i;
            }
        }
        return -1;
    }
//报表统计
   @Override
    public ArrayList<Integer> getfind() throws IOException {
        ArrayList<Student> reader = daoru();
        //男生，女生各多少人
        long nanCount = reader.stream().filter(s -> s.getGender().startsWith("男")).count();
        long nvCount = reader.stream().filter(s -> s.getGender().startsWith("女")).count();
        //18,19,20三个年龄段的学生人数
        int count18 = 0, count19 = 0, count20 = 0, sum = 0;
        for (Student student : reader) {
            Period period = Period.between(student.getBirthday(), LocalDate.now());
            int years = period.getYears();
            sum += years;
            if (years == 18) {
                count18++;
            } else if (years == 19) {
                count19++;
            } else if (years == 20) {
                count20++;
            }
        }//      获取班级总人数
        int size = reader.size();
//      班级平均年龄为
        int age = sum / size;
        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add((int) nanCount);
        list1.add((int) nvCount);
        list1.add(count18);
        list1.add(count19);
        list1.add(count20);
        list1.add(size);
        list1.add(age);
        return list1;
    }
//获取每个小组的人数
    @Override
    public HashMap<Integer, ArrayList<Student>> getGroup() throws IOException {
        ArrayList<Student> reader = daoru();
        HashMap<Integer, ArrayList<Student>> map = new HashMap<>();
        for (Student student : reader) {
            //判断集合中是否有小组数
            boolean result = map.containsKey(student.getGroup());
            //有就将新的list存入map中
            if (result) {
                ArrayList<Student> list2 = map.get(student.getGroup());
                list2.add(student);
                map.put(student.getGroup(), list2);
                //没有就将小组和List添加进去
            } else {
                ArrayList<Student> list1 = new ArrayList<>();
                list1.add(student);
                map.put(student.getGroup(), list1);
            }
        }
        return map;
    }

    //读数据
//    @Override
//    public ArrayList<Student> getReader() throws IOException {
//        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("students.txt"));
//        BufferedReader reader = new BufferedReader(new InputStreamReader(bis));
//        byte[] bytes = new byte[1024];
//        String s;
//        ArrayList<Student> list = new ArrayList<>();
//        while ((s = reader.readLine()) != null) {
//            String[] split = s.split(",");
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate date = LocalDate.parse(split[3], formatter);
//            Student student = new Student(split[0], split[1], split[2], date, split[4], Integer.parseInt(split[5]), Integer.parseInt(split[6]), split[7]);
//            list.add(student);
//        }
//        reader.close();
//        bis.close();
//        return list;
//    }
    @Override
    public void update(String id, Student stu) throws IOException {
        int index = getIndex(id);
        list.set(index, stu);
        BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"));
        for (Student student : list) {
            writer.write(student.getId() + "," + student.getName() + "," + student.getGender() + "," + student.getBirthday() + "," + student.getPhoneNum() + ","
                    + student.getAge() + "," + student.getGroup() + "," + student.getWeChatNum());
        }
        writer.close();
    }

    public void daochu(){
        HSSFWorkbook workbook = new HSSFWorkbook();
        String title = "黑马学生信息表";
        int x=1;
        HSSFSheet sheet = workbook.createSheet(title + x);
        ArrayList<HashMap<String, String>> listmap = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            HashMap<String, String> datemap = new HashMap<>();
            Student stu = list.get(i);

            String s = stu.getBirthday().toString();
            datemap.put("学号", stu.getId());
            datemap.put("姓名", stu.getName());
            datemap.put("性别", stu.getGender());
            datemap.put("生日", s);
            datemap.put("手机号", stu.getPhoneNum());
            datemap.put("年龄", stu.getAge()+"");
            datemap.put("组别", stu.getGroup()+"");
            datemap.put("微信号", stu.getWeChatNum());
            listmap.add(datemap);

        }
        String[] rousName =new String[] {"序号","学号", "姓名", "性别", "生日", "手机号", "年龄", "组别", "微信号"};
        ArrayList<Object[]> datelist = new ArrayList<>();
        Object[] objs = null;
        for (int i = 0; i < listmap.size(); i++) {
            HashMap<String, String> date = listmap.get(i);
            objs = new Object[rousName.length];
            objs[0]=i;
            objs[1] = date.get("学号");
            objs[2] = date.get("姓名");
            objs[3] = date.get("性别");
            objs[4] = date.get("生日");
            objs[5] = date.get("手机号");
            objs[6] = date.get("年龄");
            objs[7] = date.get("组别");
            objs[8] = date.get("微信号");
            datelist.add(objs);
        }
        ExportExcel ex = new ExportExcel(title, rousName, datelist);
        try {
            ex.export(workbook, sheet, x);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ArrayList<Student> daoru() {
            ArrayList<Student> students = new ArrayList<>();
            try {
                List<String[]> strings = POIUtils.readExcel(new File("D:\\code\\systemstudent02\\system\\dir\\systemstudent.xls"));
                Student student = null;
                for (int i = 1; i < strings.size(); i++) {
                    String[] strings1 = strings.get(i);

                    //System.out.println(Arrays.toString(strings1));
                    String[] split = strings1[4].split("-");
                    int year = Integer.parseInt(split[0]);
                    int month = Integer.parseInt(split[1]);
                    int day = Integer.parseInt(split[2]);
                    LocalDate birthday = LocalDate.of(year, month, day);

                    student = new Student(strings1[1], strings1[2], strings1[3], birthday, strings1[5], Integer.parseInt(strings1[6]), Integer.parseInt(strings1[7]), strings1[8]);
                    students.add(student);
                }
//                for (Student student1 : students) {
//                    System.out.println(student1);
//                }
               /* for (Student student1 : students) {
                    System.out.println(student1);
                }*/
            } catch (IOException e) {
                e.printStackTrace();
            }
        return students;
    }
    }


